package cn.edu.zafu.bigdata.Wym;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Scanner;

public class Wym_AppendAndReadFile {

    public static void appendToFile(String fileName, String content) {

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true))) {
            writer.write(content);
            writer.newLine();// 添加一个新行，以便追加的内容不会和文件中原有的内容在同一行

        } catch (IOException e) {
            System.out.println("An error occurred while appending to the file: " + e.getMessage());
        }
    }

    public static void readFile(String fileName) {
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("An error occurred while reading the file: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter your student ID:");
        String studentId = scanner.nextLine();
        String fileName = "files/" + studentId + ".txt";

        System.out.println("Enter the text you want to append to the file:");
        String content = scanner.nextLine();
        scanner.close();

        appendToFile(fileName, content);
        System.out.println("Content appended successfully. Reading file content...");
        readFile(fileName);
    }
}